package com.example.backend.service;

import com.example.backend.dto.FileDownloadResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件存储服务
 */
@Service
@Slf4j
public class FileStorageService {
    
    /**
     * 保存文件到磁盘
     */
    public void saveFile(org.springframework.web.multipart.MultipartFile file, String filePath) throws IOException {
        Path path = Paths.get(filePath);
        
        // 创建目录
        Files.createDirectories(path.getParent());
        
        // 保存文件
        try (InputStream inputStream = file.getInputStream();
             OutputStream outputStream = Files.newOutputStream(path)) {
            
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
        
        log.info("文件保存成功: {}", filePath);
    }
    
    /**
     * 从磁盘加载文件
     */
    public byte[] loadFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        
        if (!Files.exists(path)) {
            throw new IOException("文件不存在: " + filePath);
        }
        
        return Files.readAllBytes(path);
    }
    
    /**
     * 删除文件
     */
    public void deleteFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        
        if (Files.exists(path)) {
            Files.delete(path);
            log.info("文件删除成功: {}", filePath);
        } else {
            log.warn("文件不存在: {}", filePath);
        }
    }
    
    /**
     * 创建ZIP文件
     */
    public byte[] createZipFile(java.util.List<FileDownloadResult> files, String zipFileName) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        try (ZipOutputStream zos = new ZipOutputStream(baos)) {
            for (FileDownloadResult file : files) {
                if (file.isSuccess() && file.getContent() != null) {
                    ZipEntry entry = new ZipEntry(file.getFileName());
                    zos.putNextEntry(entry);
                    zos.write(file.getContent());
                    zos.closeEntry();
                }
            }
        }
        
        return baos.toByteArray();
    }
    
    /**
     * 检查文件是否存在
     */
    public boolean fileExists(String filePath) {
        return Files.exists(Paths.get(filePath));
    }
    
    /**
     * 获取文件大小
     */
    public long getFileSize(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        return Files.size(path);
    }
    
    /**
     * 移动文件
     */
    public void moveFile(String sourcePath, String targetPath) throws IOException {
        Path source = Paths.get(sourcePath);
        Path target = Paths.get(targetPath);
        
        // 创建目标目录
        Files.createDirectories(target.getParent());
        
        // 移动文件
        Files.move(source, target);
        
        log.info("文件移动成功: {} -> {}", sourcePath, targetPath);
    }
    
    /**
     * 复制文件
     */
    public void copyFile(String sourcePath, String targetPath) throws IOException {
        Path source = Paths.get(sourcePath);
        Path target = Paths.get(targetPath);
        
        // 创建目标目录
        Files.createDirectories(target.getParent());
        
        // 复制文件
        Files.copy(source, target);
        
        log.info("文件复制成功: {} -> {}", sourcePath, targetPath);
    }
    
    /**
     * 清理空目录
     */
    public void cleanupEmptyDirectories(String basePath) throws IOException {
        Path base = Paths.get(basePath);
        
        if (Files.exists(base) && Files.isDirectory(base)) {
            Files.walk(base)
                    .sorted((a, b) -> b.compareTo(a)) // 从深到浅排序
                    .filter(Files::isDirectory)
                    .forEach(dir -> {
                        try {
                            if (Files.list(dir).findAny().isEmpty()) {
                                Files.delete(dir);
                                log.info("删除空目录: {}", dir);
                            }
                        } catch (IOException e) {
                            log.warn("清理目录失败: {}", dir, e);
                        }
                    });
        }
    }
}
